package com.test.demo.controller;

import com.test.demo.common.CommonParam;
import com.test.demo.common.Constants;
import com.test.demo.common.result.Result;
import com.test.demo.entity.dto.UserInfoDTO;
import com.test.demo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@Api(tags = "用户接口")
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserService userService;

    @PostMapping("register")
    @ApiOperation("注册")
    public Result register(@RequestBody @Valid UserInfoDTO userinfoDTO) {
        String code = userinfoDTO.getValidateCode();
        String codeOld = (String) redisTemplate.opsForValue().get(Constants.CODE + userinfoDTO.getMobilePhone());
        if (StringUtils.isBlank(codeOld)) {
            return Result.fail("验证码已过期，请重新获取");
        }
        if (!code.equals(codeOld)) {
            return Result.fail("验证码不正确");
        }
        return userService.register(userinfoDTO);
    }

    @PostMapping("logout")
    @ApiOperation("登出")
    public Result logout() {
        Long userId = CommonParam.getInstance().getUserId();
        String key = Constants.APP_TOKEN + userId;
        String token = (String) redisTemplate.opsForValue().get(key);
        if (token != null) {
            redisTemplate.delete(key);
        }
        return Result.success();
    }
}
